"""
装饰器定义文件
"""

__all__ = ['complete', 'lprof', 'mprof', 'path_knight']

import os
import time
import pygame
from datetime import datetime
import winsound

from functools import wraps, partial
from memory_profiler import profile
from line_profiler import LineProfiler


class complete:
    """
    Ringing after func running over.
    """
    def __init__(self, music_path):
        self.path = music_path


    def __call__(self, func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            r = func(*args, **kwargs)
            pygame.mixer.init()
            pygame.mixer.music.load(self.path)
            pygame.mixer.music.play(1,0.0)
            time.sleep(10)
            return r

        return wrapper

def path_knight(path):
    """
    检查文件夹路径参数是否存在，如果不存在，建立并提示
    :param path:
    :return:
    """
    if not os.path.exists(path):
        print("The path didn't exist.")
        os.mkdir(path)
        print("It has been made automatically.")

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)

        return wrapper

    return decorator

def lprof(path):
    """
    保存函数的运行情况（使用line_profiler）
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            profiler = LineProfiler(func)  # 把函数传递到性能分析器
            profiler.enable()  # 开始分析
            r = func(*args, **kwargs)
            profiler.disable()  # 停止分析
            with open(path + str(datetime.now().timestamp()) + "_line_profile.log", 'w+') as fp:
                profiler.print_stats(fp)  # 打印出性能分析结果
            return r

        return wrapper

    return decorator

@path_knight("out")
def mprof(path):
    """
    保存函数的运行情况（使用memory_profiler）
    """
    time.sleep(1)
    return partial(profile, precision=4, stream=open(path + datetime.now().strftime("%Y%m%d%H%M%S") + "_memory_profile.log", 'w+'))


